package com.yj.auto.core.web.system.service;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.kit.*;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.*;
import com.yj.auto.Constants;
import com.yj.auto.core.base.annotation.*;
import com.yj.auto.core.base.model.*;
import com.yj.auto.core.jfinal.base.*;
import com.yj.auto.core.web.system.model.*;

/**
 * Org 管理 描述：
 */
@Service(name = "orgSrv")
public class OrgService extends BaseService<Org> {

	private static final Log logger = Log.getLog(OrgService.class);

	public static final String SQL_LIST = "system.org.list";

	public static final Org dao = new Org().dao();

	@Override
	public Org getDao() {
		return dao;
	}

	@Override
	public SqlPara getListSqlPara(QueryModel query) {
		if (StrKit.isBlank(query.getOrderby())) {
			query.setOrderby("sort");
		}
		return getSqlPara(SQL_LIST, query);
	}

	public boolean save(Org model) {
		boolean success = model.save();
		if (success) {
			updatePath(model);
		}
		return success;
	}

	public boolean update(Org model) {
		boolean success = model.update();
		if (success) {
			updatePath(model);
		}
		return success;
	}

	private void updatePath(Org model) {
		Org temp = model;
		String path = "," + model.getId() + ",";
		while (temp.getParentId() != 0) {
			Org parent = this.get(temp.getParentId());
			if (null == parent) {
				break;
			} else {
				path = "," + parent.getId() + path;
			}
			temp = parent;
		}
		model.setPath(path);
		model.update();
	}

	/**
	 * 根据机构层级所获取所有上级机构（包括当前机构）
	 * 
	 * @param id
	 * @return
	 */
	public List<Org> findOrgs(Integer id) {
		List<Org> list = new ArrayList<Org>();
		Org e = get(id);
		if (null != e) {
			list.add(e);
			while (e.getParentId() != 0) {
				Org parent = this.get(e.getParentId());
				if (null == parent) {
					break;
				} else {
					list.add(parent);
				}
				e = parent;
			}
		}
		return list;
	}

	// 根据机构编码查询
	public Org getByCode(String code) {
		String sql = "select * from t_sys_org where code=?";
		return dao.findFirst(sql, code);
	}

	public List<Org> children(Integer id, String state) {
		if (null == id)
			id = new Integer(0);
		QueryModel query = new QueryModel();
		query.setId(id);
		query.setState(state);
		query.setOrderby("sort");
		return find(SQL_LIST, query);
	}

	public boolean updateSort(Integer[] id) {
		if (null == id || id.length < 1)
			return false;
		List<Org> list = new ArrayList<Org>();
		for (int i = 0; i < id.length; i++) {
			Org d = new Org();
			d.setId(id[i]);
			d.setSort(i + 1);
			list.add(d);
		}
		String sql = "update t_sys_org set sort=? where id=?";
		int[] result = Db.batch(sql, "sort, id", list, 500);
		return result.length > 0;
	}
}